/****************************************************************************
** ui.h extension file, included from the uic-generated form implementation.
**
** If you want to add, delete, or rename functions or slots, use
** Qt Designer to update this file, preserving your code.
**
** You should not define a constructor or destructor in this file.
** Instead, write your code in functions called init() and destroy().
** These will automatically be called by the form's constructor and
** destructor.
*****************************************************************************/
using namespace Qt;
#include "nPatriciaTrie.h"
#include "getabsmod.h"
#include "tagdefs.h"
#include "client.h"
#include "linkedlist.h"

#include <string.h>
#include <q3popupmenu.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <qdatetime.h>

linkedlist *selectlist;
linkedlist *known;
linkedlist *suggest;
char *whichfile;

QTime timetaken;

void FindFiles::init() {
    txtTags->setFocus();
}
void FindFiles::searchClicked() {
    /*
       * tabWhichMethod->currentPageIndex()
       * 	= 0   // Flat File
       *            = 1 // Hierarchical
       */
    int count=0;
    if   ((tabWhichMethod->currentPageIndex())==1) { // Hierarchical
	linkedlist *tagslst,*tm;
	linkedlist *fileslst;
	char *tags,*pch;	
	
	timetaken = QTime(0,0);
	timetaken.restart();
	
	tags=strdup(txtTags->text());
	
	fileList->clear();
	parentList->clear();
	QString tempstring;
	tempstring=txtTags->text();
	if (tempstring.length()>0) {
	    if (!(tempstring.startsWith("/")))
		tempstring.prepend("/");
	    if (!(tempstring.endsWith("/")))
		tempstring.append("/");
	}
	lblQuery->setText(tempstring);
	childrenList->clear();
	comboParent->clear();
	if (!((strcmp(tags,"")==0)||(tags==NULL))) {
	    tagslst=new linkedlist();    
	    pch = strtok (tags,",");
	    QString tmp;
	    while (pch != NULL) {
		tmp=QString(pch);
		while (tmp.endsWith("/")) 
		    tmp.truncate(tmp.length()-1);
		if (pch[0]!='/')
		    tmp.prepend("/");
		tagslst->add((char*)tmp.ascii());
		break;
	    }
	    // --------------
	    linkedlist *slashlist,*suggest;
	    slashlist=new linkedlist();
	    known=tagslst->copyList();

	    fileslst=clientsearch(HIERARCHICAL,tagslst);
	    //slashlist=clientgetsuggestions();	    
	    slashlist = clientgetslashlist();
	    if (fileslst==NULL)
		fileslst=new linkedlist();
	    if (slashlist==NULL)
		slashlist=new linkedlist();
	    count=0;
	    while (!(fileslst->isEmpty())) {
		new Q3IconViewItem( fileList,fileslst->remove());
		count ++;
	    }
	    suggest=new linkedlist();
	    tm = known->copyList();
	    QString qst,qtmpst;
	    
	    while (!(tm->isEmpty())) {
		qst=QString(tm->remove());
		if (!(qst.startsWith("/"))) 
		    qst.prepend("/");
		while (!slashlist->isEmpty()) {
  		    
		    qtmpst=QString(slashlist->remove());
		    if (qtmpst.contains(qst))
			suggest->add((char*)qtmpst.ascii());
		}
	    }

	    QString qst1,qst2;
	    
	    linkedlist *parent ,*child;
	    parent = new linkedlist();
	    child = new linkedlist();
	    int a,b,c,d;
	    tm = known->copyList();
	    char *dirst;
	    dirst = strdup(tm->remove());
	    int prevloc;
    
	    while (!(suggest->isEmpty())) {
		qst1 = QString(suggest->remove());
		prevloc=0;
		while (prevloc!=-1) {
		    a = qst1.find(dirst,prevloc);
		    d = a+strlen(dirst)+1;
		    b=-2;c=-2;
		    if (a>=0)  {
			if (a>0)
			    b = qst1.findRev('/',a-1);
			if (((a+strlen(dirst))+1)<qst1.length())
			    c = qst1.find('/',d);
			if ((c<0)  && (c!=-2))
			    child->add((char*)(qst1.mid(d,qst1.length())).ascii());	
			if ((c>0))
			    child->add((char*)(qst1.mid(d,c-d)).ascii());
			if (b>=0) 
			    parent->add((char*)(qst1.mid(b+1,(a-b)-1).ascii()));
			prevloc=a+1;
		    }
		    else
			prevloc=a;
		}
	    }
	    parent->removeDuplicates();
	    child->removeDuplicates();
	    char *parentstring;
	    while (!(parent->isEmpty())) {
		parentstring=strdup(parent->remove());
		new Q3IconViewItem( parentList, parentstring );
		//new Q3IconViewItem( parentList, parentstring, QPixmap("images/Folder1.xcf",0,Qt::PreferDither));
		//new Q3IconViewItem( parentList, parentstring, QPixmap( ":Icons/images/Folder.png"));
		comboParent->insertItem(parentstring);
	    }
	      char *childstring;
	      while (!(child->isEmpty())) {
		  childstring=strdup(child->remove());
		new Q3IconViewItem( childrenList, childstring);
	    }
	  
	}	
    } else {
	// Flat Files
	char *tags,*pch;
	linkedlist *tagslst,*fileslst,*suggest;
	timetaken = QTime(0,0);
	timetaken.restart();
	
	tags=strdup(txtTags->text());
	flatFileList->clear();
	suggestList->clear();
	if (!((strcmp(tags,"")==0)||(tags==NULL))) {
	    tagslst=new linkedlist();    
	    pch = strtok (tags,",");
	    while (pch != NULL) {
		tagslst->add(pch);
		pch = strtok (NULL, ",");
	    }
	    // --------------
	    known=tagslst->copyList();
	    suggest=new linkedlist();
	    fileslst=clientsearch(FLATSEARCH,tagslst);
	    suggest=clientgetsuggestions();
	    //suggest = clientlistalltags();
	    //	suggest=clientflatsuggest();
	    while ((fileslst!=NULL)&&(!(fileslst->isEmpty()))) {
		new Q3IconViewItem( flatFileList, fileslst->remove());
		count ++;
	    }
	    suggest->sort();
	    known->sort();
	    if (suggest!=NULL)
		suggest->sortedselfminus(known);
	    while ((suggest!=NULL)&&(!(suggest->isEmpty()))) {
		    QString qst = QString(suggest->remove());
		    if (!qst.startsWith("/"))
		new Q3IconViewItem( suggestList, qst);
	    }	
	}
    }
    QString qst1,qst2;
    qst1=QString::fromAscii("Files Found : ");
    qst2.setNum(count,10);
    qst1.append(qst2);
    lblStatus->setText(qst1);
    qst2.setNum(timetaken.elapsed(),10); 
    qst1=QString::fromAscii("Time Taken : ");  
    qst1.append(qst2);
    qst1.append(QString(" msec(s)"));
    lblTime->setText(qst1);
//    printf("Time Taken : %s",qst2.ascii());
//    printf("Files Found : %d",count);
}

void FindFiles::addparent(Q3IconViewItem* a)
{
    char *name=strdup((a->text()).ascii());
    QString qst1 = QString(name),qst2;
    qst2 = QString(known->remove());
    if (!(qst2.startsWith("/")))
	qst2.prepend("/");
    qst1.append(qst2);
    txtTags->setText(qst1);
    searchClicked();
}

void FindFiles::makeparent(const QString& a)
{
    //if(a == NULL) {
    //}
    //else
    //{
	txtTags->setText(a);
	searchClicked();
    //}
}

void FindFiles::addchild(Q3IconViewItem* a)
{
    char *name=strdup((a->text()).ascii());
    QString qst1 = QString(name),qst2;
    qst2 = QString(known->remove());
    if (!(qst2.endsWith("/")))
	qst2.append("/");
    qst2.append(qst1);
    txtTags->setText(qst2);
    searchClicked();
}

void FindFiles::addsuggestion(Q3IconViewItem* a)
{
    char *name=strdup((a->text()).ascii());
    char *current;
    QString qst1,qst2;
    current=strdup(txtTags->text());
    qst1=QString::fromAscii(current);
    qst2=QString::fromAscii(" ");
    qst1.append(qst2);
    qst2=QString::fromAscii(name);
    qst1.append(qst2);
    txtTags->setText(qst1);
    searchClicked();
}





void FindFiles::contextMenu(Q3IconViewItem *a, const QPoint& p)
{
  int count=0;
  selectlist = new linkedlist();
  Q3IconViewItem *b;
  
  if   ((tabWhichMethod->currentPageIndex())==1) 
      b=fileList->firstItem();    // Hierarchical
  else
       b=flatFileList->firstItem(); // Flat
  while (b) {
	     if (b-> isSelected()) {
		count++;
		selectlist->add((char*)(b->text()).ascii());
	    }
                    b=b->nextItem();
	 }
  
  // no Context Sensitive menu if no item is selected
  if (count==0)
       return;
 Q3PopupMenu *context= new Q3PopupMenu(this);

  if (count==1)   {       
        char *st=strdup(selectlist->remove());
        selectlist->add(st);
        if (whichfile!=NULL)
            free(whichfile);
        whichfile=strdup(st);
        context->insertItem("&Open", this, SLOT( runfile () ) );
        //context->insertItem("Open &Folder", this, SLOT( openfolder() ) );
   }
  context->insertItem("&Tag", this, SLOT( tag()));
  context->popup(p,0);
//  printf("Selected Items : %d\n",count);
}


void FindFiles::runfile() {
   // printf("Called RunFile with :: %s\n",whichfile);
    char *params[4];
    params[0]=strdup("kfmclient");
    params[1]=strdup("exec");
    params[2]=strdup(whichfile);
    params[3]=(char*)0;
    int ret;
    pid_t PID;
    PID = fork();
    if (PID == 0) {
       ret = execl ("/usr/bin/kfmclient", "kfmclient","exec",strdup(whichfile),(char*)0);
       return;  //never comes to this
    } 
    for (int i=0;i<3;i++)
	if (params[i]!=NULL)
	    free(params[i]);
}

void FindFiles::openfolder() {
    //printf("called openfolder with :: %s\n",whichfile);  
  char *tmp;
  tmp = (char*)malloc(sizeof(char[strlen(whichfile)+5]));
  if(tmp==NULL) {
      //printf("Memory not available!!!!!!!!!!\n");
      return;
  } 
 // printf("Memory obtained!!\n");  
  strcpy(tmp,whichfile);
  strcat(tmp,"/../");
  //printf("Resolving!!! : %s\n",tmp);  
/*  if (whichfile!=NULL)
     free(whichfile);
  */ 
  strcpy(whichfile,getabsmod(tmp));
  runfile();
  free(tmp);  
}
void FindFiles::tag() {
    int count;
    count=selectlist->count()+2; 
    char **params=new char*[count]; 
    int ret;
    int i;
    params[0]="TagEditor";
    i=1;
    while (!(selectlist->isEmpty())) {
	params[i]=selectlist->remove();
	i++;
    }
    params[i]=(char*)0;
    pid_t PID;
    PID = fork();
    if (PID == 0) {
       ret = execv (tagcmd, params);
       return;  //never comes to this
    }
}

void FindFiles::openfile(Q3IconViewItem* a)
{
    char *name=strdup((a->text()).ascii());
   //printf("double clicked on %s \n",name);
   if (whichfile!=NULL)
       free(whichfile);
   whichfile=strdup(name);
   runfile();
}



